<?php

namespace App\Admin\Controllers;

use App\Models\Book;
use App\Models\BookChapter;
use App\Utils\StringUtil;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\MessageBag;

class BookChapterController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '书籍章节';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new BookChapter);
        $grid->model()->orderBy('book_id', 'desc')->orderBy('sort', 'asc');

        $grid->column('id', __('Id'));
        $grid->column('book.name', __('书籍名称'));
        $grid->column('book_id', __('书籍ID'));
        $grid->column('name', __('章节名称'))->expand(function ($model){
            $books = $model->words()->get()->map(function ($comment){
                return $comment->only([
                    'sort',
                    'en_word',
                    'cn_word',
                    'word_class',
                    'read_mark',
                    'error_syllable',
                    'symbol',
                    'paragraph',
                    'plot_remind',
                    'opt_two',
                    'opt_thr',
                    'opt_four',
                    'id'
                ]);
            });

            return new Table([
                '排序',
                '英文',
                '中文',
                '词性',
                '重读标记',
                '错误音节',
                '音标',
                '段落',
                '关联提醒',
                '选项二',
                '选项三',
                '选项四',
                'id'
            ], $books->toArray());
        });
        $grid->column('sort', __('排序'));
        // $grid->column('book_txt', __('章节内容'));
        $grid->column('word_ct', __('单词数'));
        $grid->column('is_free', __('是否免费'));
        $grid->column('price', __('价格（分）'));
        // $grid->column('paragraphs', __('段落'));
        $grid->column('paragraphs', '段落')->display(function ($paragraphs){
            $paragraphs = json_decode($paragraphs);

            return implode('/', $paragraphs);
        });
        $grid->column('created_at', __('创建时间'));
        $grid->column('updated_at', __('更新时间'));


        $grid->filter(function ($filter){
            $filter->disableIdFilter();

//            $filter->where(function ($query){
//                $query->whereHas('book', function ($query){
//                    $query->where('name', 'like', "%{$this->input}%");
//                });
//
//            }, '书籍名称');
            $filter->like('name', '章节名称');


        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(BookChapter::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('book_id', __('Book id'));
        $show->field('name', __('Name'));
        $show->field('sort', __('Sort'));
        $show->field('book_txt', __('Book txt'));
        $show->field('word_ct', __('Word ct'));
        $show->field('is_free', __('Is free'));
        //$show->field('price', __('Price'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new BookChapter);

        $bookOption = [];
        $books = Book::select(['id', 'name'])->get();
        foreach($books as $item){
            $bookOption[$item->id] = $item->name;
        }
        $form->select('book_id', '书籍')->options($bookOption)->rules('required');

        $form->text('name', __('章节名称'))->rules('required');
        $form->number('sort', __('排序'))->rules('required');
        //$form->number('word_ct', __('单词数'));
        $form->radio('is_free', __('是否免费'))->options(BookChapter::$isFreeLabels)->default(1);;
        $form->number('price', __('价格（分）'));
        $form->editor('book_txt', __('章节内容'))->rules('required');
        $form->saving(function (Form $form){
            // 自定义验证
            $words = StringUtil::parseTextContent($form->book_txt);
            $arr = [];
            foreach($words as $item){
                $arr[] = $item['en_word'];
            }
            $counts = array_count_values($arr);
            $results = array_filter($counts, function ($count){
                return $count > 1;
            });

            if (count($results) > 0){
                $error = new MessageBag([
                    'title' => '出现重复单词',
                    'message' => '重复词为：' . json_encode($results),
                ]);

                return back()->with(compact('error'));
            }
        });




        return $form;
    }
}
